<template>
    <div class="connection-form-page">
      <div class="form-header">
        <h1 class="page-title">{{ titleMap[props.enterType] }} {{ DbTypeMap[props.dbType].name }} 连接</h1>
        <el-button v-if="props.enterType === 'add'" class="return-button" type="primary" @click="handleBack" :disabled="loading" >
          <el-icon><CaretLeft /></el-icon> 返回
        </el-button>
        <el-button v-else class="return-button" type="danger" @click="handleClose" :disabled="loading" >
          <el-icon><CircleCloseFilled /></el-icon> 关闭
        </el-button>
      </div>
  
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="connection-form" >
        <!-- 基础信息 -->
        <el-card class="form-section">
          <template #header>
            <div class="card-header"> <span>基础信息</span> </div>
          </template>
          <template v-for="field in formConfig.basicFields" :key="field.prop">
            <ConnAddFormItem v-if="!field.hidden" :formData="formData" :field="field" />
          </template>
        </el-card>
  
        <!-- 认证信息 -->
        <el-card class="form-section">
          <template #header>
            <div class="card-header"><span>认证信息</span></div>
          </template>
          <template v-for="field in formConfig.authFields" :key="field.prop">
            <ConnAddFormItem v-if="!field.hidden" :formData="formData" :field="field" />
          </template>
        </el-card>
  
        <!-- 高级配置 -->
        <el-card class="form-section">
          <template #header>
            <div class="card-header"><span>高级配置</span></div>
          </template>
          <template v-for="field in formConfig.advancedFields" :key="field.prop">
            <ConnAddFormItem v-if="!field.hidden" :formData="formData" :field="field" />
          </template>
        </el-card>
  
        <!-- 表单操作 -->
        <div class="form-actions">
          <el-button type="primary" @click="handVerify" :disabled="loading" :loading="loading && loadingButton === 'verify'" >测试连接</el-button>
          <el-button type="success" @click="handSave" :disabled="loading" :loading="loading && loadingButton === 'save'" >保存</el-button>
        </div>
      </el-form>
    </div>
  </template>
  
  <script setup lang="ts">
  import type { Component } from 'vue'
  import { useRouter } from 'vue-router'
  import { ref, computed, watch, inject } from 'vue'
  import { CaretLeft, CircleCloseFilled } from '@element-plus/icons-vue'
  import { Connection } from '@/types/api/connection'
  import { databaseForms } from '@/enums/connectionTypeConst'
  import { connectionVerify, connectionSave, connectionDetail } from '@/api/connection'
  import type { BaseFormField, DatabaseFormConfig } from '@/types/api/database'
  import { ElMessage, FormInstance, FormRules, ElInput, ElInputNumber, ElSelect, ElSwitch, ElOption } from 'element-plus'
  import { DbTypeMap } from '@/enums/connectionTypeConst'
  import { titleMap } from '@/enums/connectionFormConst'
  import { FieldProps } from '@/types/connection'
  import ConnAddFormItem from '@/views/connection/ConnAddFormItem.vue'


  const loading = ref(false)
  const loadingButton = ref('')

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 常量属性 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


  // 获取表单组件类型
  const getFieldComponent = (type: string): Component => {
    switch (type) {
      case 'password':    return ElInput
      case 'number':      return ElInputNumber
      case 'textarea':    return ElInput
      case 'select':      return ElSelect
      case 'switch':      return ElSwitch
      default:            return ElInput
    }
  }

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 常量属性 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  const formRef = ref<FormInstance>()
  const formData = ref<Connection>({
    id: undefined,
    title: '',
    options: {
      type: '',
      host: '',
      url: '',
      port: undefined,
      username: '',
      password: '',
      encoding: '',
      params: ''
    },
    createdBy: '',
    createdAt: '',
    updatedBy: '',
    updatedAt: ''
  })

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 计算属性 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // 获取当前数据库的表单配置
  const formConfig = computed<DatabaseFormConfig>(() => databaseForms[props.dbType ?? ''] || {
    basicFields: [],
    authFields: [],
    advancedFields: [],
    defaultValues: {}
  })

  // 合并所有字段的验证规则
  const rules = computed<FormRules>(() => {
  const allFields = [
      ...formConfig.value.basicFields,
      ...formConfig.value.authFields,
      ...formConfig.value.advancedFields
    ]
    return buildFormRules(allFields)
  })

  // 构建表单验证规则
  const buildFormRules = (fields: BaseFormField[]): FormRules => {
    const rules: FormRules = {}
    fields.forEach(field => {
      if (field.rules) {
        rules[field.prop] = field.rules
      }
    })
    return rules
  }
    

  
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 组件传参 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // 属性参数：接收父组件传递的参数
  const props = defineProps({
    id: Number,
    dbType: {
      type: String,
      default: ''
    },
    enterType: {
      type: String,
      default: 'add'
    }
  })

  // 方法参数：关闭抽屉
  const emit = defineEmits(['close'])

  // 方法参数：更新抽屉切换方向
  const updateSlideDirection: any = inject('updateSlideDirection')

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 监听事件 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // 监听 dbType 变化，更新默认值
  watch(() => props.dbType, (newType: string) => {
    // 编辑逻辑
    if (props.id) {
      connectionDetail(props.id).then((data) => {
        formData.value = {
          ...data,
        }
      })
    } else if (newType) {
      // 获取当前数据库类型的默认值
      const defaults = formConfig.value.defaultValues
      // 合并默认值到表单数据
      formData.value = {
        ...formData.value,
        ...defaults
      }
    }
  }, { immediate: true })

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 组件事件 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // 处理返回按钮点击
  const router = useRouter()
  const handleBack = (): void => {
    updateSlideDirection(-1, 1)
    router.push({ name: 'connSelection' })
  }

  const handleClose = (): void => {
    emit('close')
  }
  
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Api 接口交互 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // 验证 数据连接
  const handVerify = async (): Promise<void> => {
    if (!formRef.value) return
    try {
      loading.value = true
      loadingButton.value = 'verify'
      await formRef.value.validate()
      const connectionData = {
        title: formData.value.title,
        ...formData.value.options
      }
      const data = await connectionVerify(connectionData)
      const message = `<span style="color: #606266"><span>数据库产品名称：${data.dbProductName}</span> | <span>数据库产品版本：${data.dbProductVersion}</span> | <span>数据库产品主版本：${data.dbMajorVersion}</span> | <span>数据库产品子版本：${data.dbMinorVersion}</span></span>`
      ElMessage({ plain: true, type: 'success', dangerouslyUseHTMLString: true, message })
    } finally {
      loading.value = false 
    }
  }


  // 保存 数据连接
  const handSave = async (): Promise<void> => {
    if (!formRef.value) return
    
    try {
      loading.value = true
      loadingButton.value = 'save'
      await formRef.value.validate()
      const data = await connectionSave(formData.value)
      ElMessage({ plain: true, type: 'success', message: '保存成功' })
      emit('close')
    } finally {
      loading.value = false 
    }
  }

  // 获取嵌套属性值
  const getNestedValue = (obj: any, path: string) => {
    return path.split('.').reduce((acc, part) => acc?.[part], obj)
  }

  // 设置嵌套属性值
  const setNestedValue = (obj: any, path: string, value: Object) => {
    const parts = path.split('.')
    const lastPart = parts.pop()!
    const target = parts.reduce((acc, part) => {
      if (!acc[part]) acc[part] = {}
      return acc[part]
    }, obj)
    target[lastPart] = value
  }

  </script>
  
  <style scoped>
  .connection-form-page {
    padding: 0px;                    /* 页面内边距 */
    height: 100%;                    /* 占满容器高度 */
    overflow-y: auto;                /* 允许垂直滚动 */
    position: relative;              /* 作为定位参考 */
    /* 隐藏滚动条 - Webkit 浏览器 */
    &::-webkit-scrollbar {
        width: 0;
        height: 0;
        display: none;
    }
    
    /* 隐藏滚动条 - Firefox */
    scrollbar-width: none;
    
    /* 隐藏滚动条 - IE/Edge */
    -ms-overflow-style: none;
  }
  
  .form-header {
    display: flex;                    /* 弹性布局 */
    justify-content: center;          /* 两端对齐 */
    align-items: center;              /* 垂直居中 */
    margin-bottom: 20px;              /* 底部间距 */
    height: 60px;
  }
  
  .page-title {
    font-size: 24px;                  /* 标题字号 */
  }

  .return-button {
    position: absolute;
    left: 20px;
    top: 20px;
  }
  
  .connection-form {
    max-width: 800px;                /* 限制表单最大宽度 */
    margin: 0 auto;                  /* 水平居中 */
  }
  
  .form-section {
    margin-bottom: 20px;              /* 卡片间距 */
  }
  
  .card-header {
    font-size: 16px;                  /* 卡片标题字号 */
    font-weight: bold;                /* 加粗 */
  }
  
  .form-actions {
    display: flex;                   /* 弹性布局 */
    justify-content: center;         /* 水平居中 */
    gap: 16px;                       /* 按钮间距 */
    margin-top: 30px;               /* 顶部间距 */
    margin-bottom: 20px;            /* 底部间距 */
  }

  .title-wrapper {
    display: flex;
    gap: 12px;
  }

  .switch-description {
    margin-left: 10px; /* 添加左边距 */
    color: #606266;    /* 设置颜色 */
  }



  </style>